<template>
  <div v-if="drawerType === 'execute'" class="add-equip-detail">
    <px-scrollbar class="add-equip-content">
      <EditDropDown dropdownTitle="备件更换">
        <template v-slot:content>
          <px-button style="margin-bottom: 8px" type="primary" plain @click="sparePartsVisible = true">关联备件出库单</px-button>
          <px-table :data="sparePartsTableData" class="equip-table" size="small" max-height="400" border>
            <px-table-column type="expand" width="40">
              <template #default="props">
                <div style="padding-left: 40px">
                  <px-table :data="props.row.sparePartInventoryDTOList" border>
                    <px-table-column
                      v-for="(item, index) in childSparePartsTableColumns"
                      :key="index"
                      :label="item.label"
                      :min-width="item.minWidth"
                      :align="item.align"
                      :show-overflow-tooltip="item.showOverflowTooltip"
                      :fixed="item.fixed"
                    >
                      <template #default="scope">{{
                        scope.row[item.prop] === 0 ? scope.row[item.prop] : scope.row[item.prop] ? scope.row[item.prop] : "-"
                      }}</template>
                    </px-table-column>
                  </px-table>
                </div>
              </template>
            </px-table-column>
            <px-table-column type="index" label="序号" width="60" />
            <px-table-column
              v-for="(item, index) in sparePartsTableColumns"
              :key="index"
              :label="item.label"
              :min-width="item.minWidth"
              :align="item.align"
              :show-overflow-tooltip="item.showOverflowTooltip"
              :fixed="item.fixed"
            >
              <template #default="scope">
                {{ scope.row[item.prop] === 0 ? scope.row[item.prop] : scope.row[item.prop] ? scope.row[item.prop] : "-" }}
              </template>
            </px-table-column>
            <px-table-column v-if="drawerType === 'execute'" fixed="right" label="操作" width="120" align="center">
              <template #default="scope">
                <px-tooltip content="删除" placement="top">
                  <px-button link type="danger" icon="Delete" @click="sparePartsDelete(scope.$index)" />
                </px-tooltip>
              </template>
            </px-table-column>
          </px-table>
        </template>
      </EditDropDown>
      <EditDropDown dropdownTitle="工具领用">
        <template v-slot:content>
          <px-button style="margin-bottom: 8px" type="primary" plain @click="toolVisible = true">关联工具领用单</px-button>
          <px-table :data="toolTableData" class="equip-table" size="small" max-height="400" border>
            <px-table-column type="expand" width="40">
              <template #default="props">
                <div style="padding-left: 40px">
                  <px-table :data="props.row.chooseToolBorrowDetailDTOList" border>
                    <px-table-column
                      v-for="(item, index) in childToolTableColumns"
                      :key="index"
                      :label="item.label"
                      :min-width="item.minWidth"
                      :align="item.align"
                      :show-overflow-tooltip="item.showOverflowTooltip"
                      :fixed="item.fixed"
                    >
                      <template #default="scope">
                        <px-tag
                          v-if="item.tag"
                          effect="plain"
                          :style="{
                            color: 'rgba(0, 0, 0, 0.8)',
                            border: `1px solid ${scope.row.revertStatus === 1 ? '#4CCBA1' : '#F7B648'}`,
                            backgroundColor: `${scope.row.revertStatus === 1 ? '#E8F8F3' : '#FEF5E6'}`
                          }"
                        >
                          {{ scope.row.revertStatusDesc }}
                        </px-tag>
                        <span v-else>{{
                          scope.row[item.prop] === 0 ? scope.row[item.prop] : scope.row[item.prop] ? scope.row[item.prop] : "-"
                        }}</span>
                      </template>
                    </px-table-column>
                  </px-table>
                </div>
              </template>
            </px-table-column>
            <px-table-column type="index" label="序号" width="60" />
            <px-table-column
              v-for="(item, index) in toolTableColumns"
              :key="index"
              :label="item.label"
              :min-width="item.minWidth"
              :align="item.align"
              :show-overflow-tooltip="item.showOverflowTooltip"
              :fixed="item.fixed"
            >
              <template #default="scope">{{
                scope.row[item.prop] === 0 ? scope.row[item.prop] : scope.row[item.prop] ? scope.row[item.prop] : "-"
              }}</template>
            </px-table-column>
            <px-table-column v-if="drawerType === 'execute'" fixed="right" label="操作" width="120" align="center">
              <template #default="scope">
                <px-tooltip content="删除" placement="top">
                  <px-button link type="danger" icon="Delete" @click="toolDelete(scope.$index)" />
                </px-tooltip>
              </template>
            </px-table-column>
          </px-table>
        </template>
      </EditDropDown>
    </px-scrollbar>
    <div class="info-form-btns">
      <px-button type="primary" @click="handleSubmit">保存进度</px-button>
      <px-button
        v-if="drawerType !== 'view' && [4, 6].includes(taskDetailData.workOrderStatus) && userId === taskDetailData.executorId"
        type="primary"
        @click="emits('handleFinish')"
      >
        完成维修
      </px-button>
      <px-button @click="backMainPage">取消</px-button>
    </div>
    <!-- 备件弹窗 -->
    <SparePartsDialog
      :visible="sparePartsVisible"
      :className="props.className"
      @closeDialog="sparePartsVisible = false"
      @addEquipDialog="addSpareParts"
    />
    <!-- 工具弹窗 -->
    <ToolDialog :visible="toolVisible" :className="props.className" @closeDialog="toolVisible = false" @addEquipDialog="addTool" />
  </div>
  <div v-else class="view-equip-detail-wrap">
    <px-scrollbar class="view-equip-detail">
      <div class="view-equip-title">备件更换</div>
      <px-table :data="sparePartsTableData" class="equip-table" size="small" max-height="400" border>
        <px-table-column type="expand" width="40">
          <template #default="props">
            <div style="padding-left: 40px">
              <px-table :data="props.row.sparePartInventoryDTOList" border>
                <px-table-column
                  v-for="(item, index) in childSparePartsTableColumns"
                  :key="index"
                  :label="item.label"
                  :min-width="item.minWidth"
                  :align="item.align"
                  :show-overflow-tooltip="item.showOverflowTooltip"
                  :fixed="item.fixed"
                >
                  <template #default="scope">{{
                    scope.row[item.prop] === 0 ? scope.row[item.prop] : scope.row[item.prop] ? scope.row[item.prop] : "-"
                  }}</template>
                </px-table-column>
              </px-table>
            </div>
          </template>
        </px-table-column>
        <px-table-column type="index" label="序号" width="60" />
        <px-table-column
          v-for="(item, index) in sparePartsTableColumns"
          :key="index"
          :label="item.label"
          :min-width="item.minWidth"
          :align="item.align"
          :show-overflow-tooltip="item.showOverflowTooltip"
          :fixed="item.fixed"
        >
          <template #default="scope">
            {{ scope.row[item.prop] === 0 ? scope.row[item.prop] : scope.row[item.prop] ? scope.row[item.prop] : "-" }}
          </template>
        </px-table-column>
        <px-table-column v-if="drawerType === 'execute'" fixed="right" label="操作" width="120" align="center">
          <template #default="scope">
            <px-tooltip content="删除" placement="top">
              <px-button link type="danger" icon="Delete" @click="sparePartsDelete(scope.$index)" />
            </px-tooltip>
          </template>
        </px-table-column>
      </px-table>
      <div class="view-equip-title" style="margin-top: 32px">工具领用</div>
      <px-table :data="toolTableData" class="equip-table" size="small" max-height="400" border>
        <px-table-column type="expand" width="40">
          <template #default="props">
            <div style="padding-left: 40px">
              <px-table :data="props.row.chooseToolBorrowDetailDTOList" border>
                <px-table-column
                  v-for="(item, index) in childToolTableColumns"
                  :key="index"
                  :label="item.label"
                  :min-width="item.minWidth"
                  :align="item.align"
                  :show-overflow-tooltip="item.showOverflowTooltip"
                  :fixed="item.fixed"
                >
                  <template #default="scope">
                    <px-tag
                      v-if="item.tag"
                      effect="plain"
                      :style="{
                        color: 'rgba(0, 0, 0, 0.8)',
                        border: `1px solid ${scope.row.revertStatus === 1 ? '#4CCBA1' : '#F7B648'}`,
                        backgroundColor: `${scope.row.revertStatus === 1 ? '#E8F8F3' : '#FEF5E6'}`
                      }"
                    >
                      {{ scope.row.revertStatusDesc }}
                    </px-tag>
                    <span v-else>{{ scope.row[item.prop] === 0 ? scope.row[item.prop] : scope.row[item.prop] ? scope.row[item.prop] : "-" }}</span>
                  </template>
                </px-table-column>
              </px-table>
            </div>
          </template>
        </px-table-column>
        <px-table-column type="index" label="序号" width="60" />
        <px-table-column
          v-for="(item, index) in toolTableColumns"
          :key="index"
          :label="item.label"
          :min-width="item.minWidth"
          :align="item.align"
          :show-overflow-tooltip="item.showOverflowTooltip"
          :fixed="item.fixed"
        >
          <template #default="scope">{{
            scope.row[item.prop] === 0 ? scope.row[item.prop] : scope.row[item.prop] ? scope.row[item.prop] : "-"
          }}</template>
        </px-table-column>
        <px-table-column v-if="drawerType === 'execute'" fixed="right" label="操作" width="120" align="center">
          <template #default="scope">
            <px-tooltip content="删除" placement="top">
              <px-button link type="danger" icon="Delete" @click="toolDelete(scope.$index)" />
            </px-tooltip>
          </template>
        </px-table-column>
      </px-table>
    </px-scrollbar>
  </div>
</template>

<script setup lang="ts">
import { querySparePartsAndTool, saveSparePartsAndTool } from "@/api/equip/maintain";
import EditDropDown from "@/views/all/equip/components/EditDropDown.vue";
import { PxMessage, PxMessageBox } from "px-ui";
import { reactive, toRefs, watchEffect } from "vue";
import SparePartsDialog from "./SparePartsDialog.vue";
import ToolDialog from "./ToolDialog.vue";

// 调用父级-返回主页、查询列表方法
const emits = defineEmits(["backMainPage", "handleFinish"]);
const props = defineProps(["taskId", "activeName", "drawerType", "className", "userId", "taskDetailData"]);
const preName = defineModel("preName");

const state = reactive<any>({
  sparePartsTableData: [],
  sparePartsTableColumns: [
    { prop: "outNum", label: "出库单号", minWidth: "160", showOverflowTooltip: true },
    { prop: "categoryDesc", label: "种类", minWidth: "160", showOverflowTooltip: true },
    { prop: "classNameDesc", label: "科室", minWidth: "140", showOverflowTooltip: true },
    // { prop: "systemValDesc", label: "系统", minWidth: "140", showOverflowTooltip: true },
    { prop: "usedDesc", label: "用途", minWidth: "140", showOverflowTooltip: true },
    { prop: "recipientName", label: "领用人", minWidth: "120", showOverflowTooltip: true },
    { prop: "outDate", label: "领用时间", minWidth: "160", showOverflowTooltip: true }
  ],
  childSparePartsTableColumns: [
    { prop: "sparePartCode", label: "备件编码", minWidth: "140", showOverflowTooltip: true },
    { prop: "sparePartName", label: "备件名称", minWidth: "140", showOverflowTooltip: true },
    { prop: "categoryDesc", label: "种类", minWidth: "160", showOverflowTooltip: true },
    { prop: "quantity", label: "领取数量", minWidth: "120", showOverflowTooltip: true },
    { prop: "returnQuantity", label: "退库数量", minWidth: "120", showOverflowTooltip: true }
  ],
  sparePartsVisible: false,
  toolTableData: [],
  toolTableColumns: [
    { prop: "toolBorrowCode", label: "领用工单号", minWidth: "180", showOverflowTooltip: true },
    { prop: "classNameDesc", label: "借用人科室", minWidth: "140", showOverflowTooltip: true },
    { prop: "toolBorrowerName", label: "领用人", minWidth: "140", showOverflowTooltip: true },
    { prop: "toolBorrowDate", label: "领用时间", minWidth: "160", showOverflowTooltip: true }
  ],
  childToolTableColumns: [
    { prop: "toolCode", label: "工具编码", minWidth: "160", showOverflowTooltip: true },
    { prop: "toolName", label: "工具名称", minWidth: "160", showOverflowTooltip: true },
    { prop: "toolCategoryDesc", label: "工具分类", minWidth: "160", showOverflowTooltip: true },
    { prop: "toolUnitDesc", label: "单位", minWidth: "160", showOverflowTooltip: true },
    { prop: "revertStatus", label: "领取状态", minWidth: "140", showOverflowTooltip: true, tag: true },
    { prop: "toolReverterName", label: "归还人", minWidth: "140", showOverflowTooltip: true },
    { prop: "toolRevertDate", label: "归还时间", minWidth: "160", showOverflowTooltip: true }
  ],
  MaintainSpareParts: "",
  MaintainTool: "",
  toolVisible: false
});
const {
  sparePartsTableData,
  sparePartsTableColumns,
  childSparePartsTableColumns,
  sparePartsVisible,
  MaintainTool,
  MaintainSpareParts,
  toolTableData,
  toolTableColumns,
  childToolTableColumns,
  toolVisible
} = toRefs(state);

watchEffect(async () => {
  if (props.activeName === "third") {
    const res = await querySparePartsAndTool({ id: props.taskId });
    sparePartsTableData.value = res.inventoryOutList || [];
    toolTableData.value = res.chooseToolBorrowRevertDTOList || [];
    if (props.drawerType === "execute") {
      MaintainSpareParts.value = JSON.stringify(sparePartsTableData.value);
      MaintainTool.value = JSON.stringify(toolTableData.value);
    }
  } else if (preName.value === "third") {
    if (props.drawerType !== "execute") {
      preName.value = "";
      return;
    }
    if (JSON.stringify(sparePartsTableData.value) !== MaintainSpareParts.value || JSON.stringify(toolTableData.value) !== MaintainTool.value) {
      PxMessageBox.confirm("切换页签会导致“备件/工具”内容无法保存，确定要切换吗？", "提示", {
        confirmButtonText: "保存进度",
        cancelButtonText: "取消保存",
        type: "warning",
        draggable: true
      })
        .then(async () => {
          handleSubmit();
          preName.value = "";
        })
        .catch(() => {
          preName.value = "";
        });
    } else {
      preName.value = "";
    }
  }
});

// 删除备件行
const sparePartsDelete = index => {
  sparePartsTableData.value.splice(index, 1);
};
// 删除工具行
const toolDelete = index => {
  toolTableData.value.splice(index, 1);
};
// 取消，返回主页面
const backMainPage = () => {
  emits("backMainPage");
};
// 保存进度
const handleSubmit = async () => {
  const arr1 = [];
  const arr2 = [];
  sparePartsTableData.value.forEach(item => {
    arr1.push(item.id);
  });
  toolTableData.value.forEach(item => {
    arr2.push(item.id);
  });
  const params = {
    workOrderId: props.taskId,
    sparePartIds: arr1,
    toolIds: arr2
  };
  await saveSparePartsAndTool(params);
  PxMessage.success("保存进度成功");
  MaintainSpareParts.value = JSON.stringify(sparePartsTableData.value);
  MaintainTool.value = JSON.stringify(toolTableData.value);
};
const addSpareParts = val => {
  if (val && val.length > 0) {
    const arr = [];
    sparePartsTableData.value.forEach(item => {
      if (item.outNum) {
        arr.push(item.outNum);
      }
    });
    const arr2 = [];
    val.forEach(item => {
      if (!arr.includes(item.outNum)) {
        arr2.push(item);
      }
    });
    sparePartsTableData.value = [...arr2, ...sparePartsTableData.value];
  }
};
const addTool = val => {
  if (val && val.length > 0) {
    const arr = [];
    toolTableData.value.forEach(item => {
      if (item.toolBorrowCode) {
        arr.push(item.toolBorrowCode);
      }
    });
    const arr2 = [];
    val.forEach(item => {
      if (!arr.includes(item.toolBorrowCode)) {
        arr2.push(item);
      }
    });
    toolTableData.value = [...arr2, ...toolTableData.value];
  }
};
</script>
<style lang="scss" scoped>
// @import url("@/views/all/equip/scss/add-detail.scss");
// @import url("@/views/all/equip/scss/view-detail.scss");
@import url("./style.scss");

.add-equip-detail {
  .add-equip-content {
    height: calc(100vh - 500px);
    padding: 0 0 24px;
    box-sizing: border-box;
  }
}

.view-equip-detail-wrap {
  .view-equip-detail {
    height: calc(100vh - 444px);
    padding: 0;
    box-sizing: border-box;
  }
}
</style>
